package com.atguigu.tingshu.order.consumer;


import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.order.service.OrderInfoService;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import lombok.extern.log4j.Log4j2;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;

/***
 * 订单超时消费者
 */
@Component
@Log4j2
public class OrderTimeoutConsumer {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private OrderInfoService orderInfoService;

    @Autowired
    private RedisTemplate redisTemplate;

    @SneakyThrows
    @RabbitListener(queues = "Order_TimeOut_Cancel_Queue")
    public void OrderTimeout(Channel channel, Message message){
        //接受队列消息
        String orderNo = new String(message.getBody());
        //获取消息属性
        MessageProperties messageProperties = message.getMessageProperties();
        //获取消息编号
        long deliveryTag = messageProperties.getDeliveryTag();
        //消息确认
        try {
            //取消订单
            orderInfoService.cancelOrder(orderNo);
            channel.basicAck(deliveryTag,false);
        } catch (Exception e){
            //判断是否第一次,如果不是记录mysql/redis/日志
            if(messageProperties.getRedelivered()){
                redisTemplate.opsForSet().add("TimeOutCancleOrderFail", orderNo);
                //丢弃消息
                channel.basicReject(deliveryTag, false);
            }else{
                //否则再来一次
                channel.basicReject(deliveryTag, true);
            }
        }
    }
}
